﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using  ZhongJia.Lock.Infrastructure;

namespace ZhongJia.Lock.Web.Filters
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILogger _logger;

        public GlobalExceptionFilter(
            ILoggerFactory logger)
        {
            _logger = logger.CreateLogger<GlobalExceptionFilter>();
        }

        public void OnException(ExceptionContext context)
        {
            var ex = context.Exception;
            if (ex is UserFriendlyException)
            {
                var userFriendlyException = (UserFriendlyException)ex;
                context.Result = new JsonResult(new
                {
                    successed = false,
                    message = userFriendlyException.Message,
                    Code = userFriendlyException.Code
                });
            }
            else if (ex is UnauthorizedAccessException || ex.InnerException is UnauthorizedAccessException)
            {
                context.Result = new UnauthorizedResult();
            }
            else
            {
                _logger.LogError(ex.Message, context.Exception);
            }
        }
    }
}
